package ooday03;

public class PolymorphicDemo {
    public static void main(String[] args) {
        //向下造型
        /*
        Animal a = new Dog("小黑",2, "黑");
        Dog d = (Dog) a;
        Swim s = (Swim) a;
        // Fish f = (Fish) a; //ClassCastException 类型转换异常
        System.out.println(a instanceof Dog); //true
        System.out.println(a instanceof Swim); //true
        System.out.println(a instanceof Fish); //false

         */

        /*
        Master master = new Master();
        Dog dogs = new Dog("小黑",2, "黑");
        Chick chicks = new Chick("小鸡",1,"白");
        Fish fishs = new Fish("鱼儿",1,"金");
        master.feed(dogs);
        master.feed(chicks);
        master.feed(fishs);

         */


        Animal[] animals = new Animal[5];
        animals[0] = new Dog("小黑", 2, "黑");
        animals[1] = new Chick("小鸡", 1, "白");
        animals[2] = new Fish("鱼儿", 1, "金");
        animals[3] = new Dog("小黄", 2, "黄");
        animals[4] = new Chick("小鸭", 1, "白");
        for (int i = 0; i < animals.length; i++) {
            System.out.println(animals[i].name);//输出每个动物的名字
            animals[i].eat();
            animals[i].drink();
            //狗：看家/游泳，游泳，鸡下蛋
            if(animals[i] instanceof Dog){
                Dog a = (Dog) animals[i];
                a.lookHome();
            }
            if (animals[i] instanceof Chick) {
                Chick c = (Chick) animals[i];
                c.layEggs();
            }
            //适用于所有实现Swim接口的类（会游泳）
            if (animals[i] instanceof Swim) {
                Swim s = (Swim) animals[i];
                s.swim();
            }
        }
    }
}

